<?php

// @formatter:off
/**
 * @file WCDirectoryMover.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-05-04 01:33:52 +0000 (Sun, 04 May 2014) $
 *
 * $Id: WCDirectoryMover.php 111 2014-05-04 01:33:52Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/includes/rules/WCDirectoryMover.php $
 */
// @formatter:on

class WCActiveTagDirectoryMover extends WCActiveTagHook {
	//
	// Public class properties.
	const Prefix = "MOVE";
	/**
	 * @var WCConnection Database pointer shortcut.
	 */
	protected $_db = false;
	/**
	 * @var string Database tables' prefix shortcut.
	 */
	protected $_dbprefix = false;
	/**
	 * Class constructor
	 */
	public function __construct() {
		// @{
		$this->_canIt["add"]["CL"] = false;
		$this->_canIt["add"]["CX"] = defined("__CRON__");
		$this->_canIt["add"]["DI"] = defined("__CRON__");
		$this->_canIt["add"]["IM"] = defined("__CRON__");
		$this->_canIt["add"]["TA"] = false;

		$this->_canIt["remove"]["CL"] = false;
		$this->_canIt["remove"]["DI"] = false;
		$this->_canIt["remove"]["TA"] = false;
		// @}
		//
		// Loading shortcuts.
		// @{
		$this->_db = WCConnection::Instance();
		$this->_dbprefix = $this->_db->prefix();
		// @}

		parent::__construct();
	}
	//
	// Public methods.
	public function hasCronTasks() {
		return true;
	}
	public function runCronTasks($spacer = "") {
		//
		// Setting default value to be returned.
		$retry = false;
		//
		// Loading working data @{
		$tag = $this->tag();
		$group = $tag->group();
		$match = false;
		preg_match("/".self::Prefix.":(.*)/", $tag->name, $match);
		$dirName = $match[1];
		$dirList = WCDirectoriesHolder::I()->itemByNameInGroup($dirName, $group);
		$directory = array_shift($dirList);
		// @}
		//
		// Moving items.
		$infoText = false;
		$count = $this->tagToDirectory($tag, $directory, "{$spacer}\t", $infoText);

		if($count > 0) {
			echo "{$spacer}Tag: {$tag}\n";
			echo "{$spacer}Directory: {$directory}\n";
			echo $infoText;
			$retry = true;
		}

		return $retry;
	}
	//
	// Protected methods.
	protected function tagToDirectory(WCTag &$tag, WCDirectory &$directory, $spacer = "", &$infoText = "") {
		$count = 0;

		$infoText = "";
		foreach($tag->comicsFull() as $comic) {
			$infoText.= "{$spacer}Moving comic '{$comic}' to directory '{$directory}': ";
			if($comic->isTrashed() || $comic->directory == $directory->id) {
				$infoText.= WCColorText::ShellYellow("Ignored").($comic->isTrashed() ? " (it's trashed)\n" : " (already at its destination)\n");
				$infoText.= "{$spacer}Removing comic '{$comic}' from tag '{$tag}': ";
				$infoText.= WCColorText::ShellGreen("Done\n");
				$tag->removeComic($comic);

				$count++;
			} elseif(is_file("{$directory->path()}/{$comic->name}")) {
				$infoText.= WCColorText::ShellRed("Failed").": File '{$directory->path()}/{$comic->name}' already exists\n";
			} elseif($comic->setDirectory($directory)) {
				$infoText.= WCColorText::ShellGreen("Done\n");
				$infoText.= "{$spacer}Removing comic '{$comic}' from tag '{$tag}': ";
				$infoText.= WCColorText::ShellGreen("Done\n");
				$tag->removeComic($comic);

				$count++;
			} else {
				$infoText.= WCColorText::ShellRed("Failed\n");
			}
		}
		foreach($tag->imagesFull() as $image) {
			$infoText.= "{$spacer}Moving image '{$image}' to directory '{$directory}': ";
			if($image->isTrashed() || $image->directory == $directory->id) {
				$infoText.= WCColorText::ShellYellow("Ignored").($image->isTrashed() ? " (it's trashed)\n" : " (already at its destination)\n");
				$infoText.= "{$spacer}Removing image '{$image}' from tag '{$tag}': ";
				$tag->removeImage($image);
				$infoText.= WCColorText::ShellGreen("Done\n");

				$count++;
			} elseif(is_file("{$directory->path()}/{$image->name}")) {
				$infoText.= WCColorText::ShellRed("Failed").": File '{$directory->path()}/{$image->name}' already exists\n";
			} elseif($image->setDirectory($directory)) {
				$infoText.= WCColorText::ShellGreen("Done\n");
				$infoText.= "{$spacer}Removing image '{$image}' from tag '{$tag}': ";
				$tag->removeImage($image);
				$infoText.= WCColorText::ShellGreen("Done\n");

				$count++;
			} else {
				$infoText.= WCColorText::ShellRed("Failed\n");
			}
		}
	}
	//
	// Public class methods.
	public static function GenActiveTagsHooks() {
		$db = WCConnection::Instance();
		$dbprefix = $db->prefix();

		$stmt = null;
		$stmtId = __CLASS__."::".__FUNCTION__;
		if($db->has($stmtId)) {
			$stmt = $db->get($stmtId);
		} else {
			$query = "select  *\n";
			$query .= "from    {$dbprefix}tags\n";
			$query .= "where   tag_name in (\n";
			$query .= "                select  concat('".self::Prefix.":', dir_name)\n";
			$query .= "                from    {$dbprefix}directories\n";
			$query .= "                where   dir_group = tag_group\n";
			$query .= "                 and    dir_lost =  'N')\n";
			$query .= "order by tag_name asc\n";

			$stmt = $db->prepare($stmtId, $query);
		}

		if($stmt->execute()) {
			global $wcActiveTagHooks;

			foreach($stmt->fetchAll() as $row) {
				if(preg_match("/".self::Prefix.":\/(.*)/", $row["tag_name"])) {
					if(!isset($wcActiveTagHooks[$row["tag_name"]])) {
						$wcActiveTagHooks[$row["tag_name"]] = array(
							"groups" => array(
								$row["tag_group"]
							),
							"description" => "DirectoryMover: '{$row["tag_name"]}'",
							"class" => "WCActiveTagDirectoryMover"
						);
					} else {
						$wcActiveTagHooks[$row["tag_name"]]["groups"][] = $row["tag_group"];
					}
				}
			}
		}
	}
}
